<template>
    <view id="ccii_login_wx">
        <view class="content">
            <!-- <view class="back" @click="$router.back()"><i class="iconfont icon-zuojiantou"></i></view> -->
            <!-- <p class="fs_32 c_333">绑定手机号</p> -->
            <view class="input_box fs_28">
                <input type="tel" v-model.trim="mobile" maxlength="11" placeholder="请输入手机号码" @keyup="mobile=mobile.replace(/\D/g,'')">
                <icon class="iconfont icon-guanbi1" v-if="hasMobile" @click="mobile=''"></icon>
                <button class="code_btn" :class="isRightMobile?'c_blue':'c_999'" @click="isRightMobile&&codetxt=='获取验证码'&&openTencentCaptcha()" v-html="codetxt"></button>
            </view>
            <view v-show="isShowCodeInput" class="codes">
                <input class="hidden_input" ref="hidden_input" type="digit" maxlength="6" v-model="code" @paste="handlePaste($event)" @keyup="code=code.replace(/\D/g,'')">
                <!-- <van-password-input :value="code" :gutter="10" :length="6" :mask="false" :focused="showKeyboard" @focus="showKeyboard = true" /> -->
				<view class="input_code">
					<view class="ul">
						<view class="li">{{code.length>=1?code[0]:''}}</view>
						<view class="li">{{code.length>=2?code[1]:''}}</view>
						<view class="li">{{code.length>=3?code[2]:''}}</view>
						<view class="li">{{code.length>=4?code[3]:''}}</view>
						<view class="li">{{code.length>=5?code[4]:''}}</view>
						<view class="li">{{code.length>=6?code[5]:''}}</view>
					</view>
				</view>
            </view>
            <!-- <van-number-keyboard @input="handleChange" @delete="handleDelete" :show="showKeyboard" @blur="showKeyboard = false" /> -->
            <button class="btn" @click="handleNext">下一步</button>
        </view>
    </view>
</template>

<script>
import { checkImage } from "@/api/common/index.js"
import { getCaptcha, checkMobileExist, updateWxUserInfo, checkUserStatus, weChatFastRegister } from "@/api/login/index.js"
// import store from '@/store'
// import * as types from '@/store/actions-type'
export default {
    data() {
        return {
            // showKeyboard: false,
            isShowCodeInput: false,
            mobile: '',
            code: '',
            timer: null,
            codetxt: '获取验证码',
        };
    },
    mounted() {
        
    },
    computed: {
        isRightMobile() {
            return this.$regular.checkPhone(this.mobile)
        },
        hasMobile() {
            if (this.mobile) {
                return true
            }
            return false
        }
    },
    methods: {
        handlePaste(e) {
            e.clipboardData.items[0].getAsString((str) => {
                if (!/^[0-9]*$/.test(str.trim())) {
                    str = ''
                }
                this.code = str;
            })
        },
        // handleChange(val) {
        //     if (this.code.length == 6) return;
        //     this.code += val
        // },
        // handleDelete() {
        //     this.code = this.code.substring(0, this.code.length - 1);
        // },
        // 触发滑块验证
        openTencentCaptcha() {
            let Imgcaptcha = new TencentCaptcha("2080837798", res => {
                if (res.ret === 0) {
                    this.handleCheckImage(res)
                } else {
					uni.showToast({title: "请完成滑块验证", icon: "none"})
                }
            }, {});
            Imgcaptcha.show();
        },
        // 校验图形验证码
        async handleCheckImage(v) {
            let res = await checkImage({
                randstr: v.randstr,
                ticket: v.ticket
            })
            if (res.code==0 && res.data.CaptchaCode==1) {
                this.getCode()
            } else {
				uni.showToast({title: res.data.CaptchaMsg, icon: "none"})
            }
        },
        // 获取短信验证码
        async getCode() {
            let res = await getCaptcha({mobile: this.mobile});
            if (res.code == 0) {
				uni.showToast({title: "验证码已发送"})
                this.isShowCodeInput = true
                let n = 120;
                this.timer = setInterval(() => {
                    this.codetxt = `${n--}s`;
                    if (n == 0) {
                        this.codetxt = "获取验证码";
                        clearInterval(this.timer);
                    }
                }, 1000);
            } else {
                this.isShowCodeInput = false
				uni.showToast({title: res.msg, icon: "none"})
            }
        },
        // 下一步
        async handleNext() {
            if (!this.isRightMobile) {
				uni.showToast({title: "请输入正确手机号", icon: "none"})
                return
            }
            if (!this.code) {
				uni.showToast({title: "请输入正确验证码", icon: "none"})
                return
            }
            // 检查手机号是否已注册
            let res = await checkMobileExist({mobile: this.mobile})
            if (res.code == 0) {
                if (res.data) {
                    if (res.data.openid) {
                        // 此手机号已被其他微信绑定
						uni.showToast({title: "当前手机号已绑定，请更换", icon: "none"})
                    } else {
                        // 此手机号已注册未绑定微信
                        this.handleUpdateWxUserInfo(res.data.id, uni.getStorageSync('openid'))
                    }
                } else {
                    // 手机号未注册
                    this.handleWxFastRegister()
                }
            } else {
                uni.showToast({title: res.msg, icon: "none"})
            }
        },
        async handleWxFastRegister() {
            let res = await weChatFastRegister({
                captcha: this.code,
                mobile: this.mobile,
                openid: uni.getStorageSync('openid'),
                platformSource: 21,
                promoterNumber: uni.getStorageSync("h5_promoterNumber")
            })
            if (res.code === 0) {
                let status = res.data.shopCompany.examineType
                // -1 未认证 0 审核中 1 已认证 2 审核失败
                if (status == -1) {
                    this.handleSaveLoginInfo(res, status, 2)
                } else if (status == 0) {
                    this.handleSaveLoginInfo(res, status, 2)
                } else if (status == 1) {
                    this.handleSaveLoginInfo(res, status, 2)
                } else if (status == 2) {
                    this.handleSaveLoginInfo(res, status, 2)
                }
            } else {
                uni.showToast({title: res.msg, icon: "none"})
            }
        },
        async handleUpdateWxUserInfo(userId, openid) {
            let res = await updateWxUserInfo({id:userId, openid})
            if (res.code == 0) {
                checkUserStatus({companyId: '', userId}).then(res => {
                    if (res.code == 0) {
                        let status = res.data.shopCompany.examineType
                        // -1 未认证 0 审核中 1 已认证 2 审核失败
                        if (status == -1) {
                            this.handleSaveLoginInfo(res, status)
                        } else if (status == 0) {
                            this.handleSaveLoginInfo(res, status)
                        } else if (status == 1) {
                            this.handleSaveLoginInfo(res, status)
                        } else if (status == 2) {
                            this.handleSaveLoginInfo(res, status)
                        }
                    } else {
                        uni.showToast({title: res.msg, icon: "none"})
                    }
                })
            } else {
                uni.showToast({title: res.msg, icon: "none"})
            }
        },
        handleSaveLoginInfo(res, stu, type='') {
			console.log(type)
            // store.commit(types.SET_USERACCOUNTSTATUS, stu)
            // store.commit(types.SET_LOGINTYPE, 'wx')
            // store.commit(types.SET_USERINFO, res.data)
            // store.commit(types.SET_AVATAR, res.data.user.headImage)
            // store.commit(types.SET_OPENID, res.data.user.openid)
			uni.setStorageSync('userId', res.data.user.id)
			uni.setStorageSync('userInfo', JSON.stringify(res.data))
            if (type == 2) {
                // 未注册  去选择身份页面
                // this.$router.push('/login/chooseIdentity')
                // 默认买家
				this.$handleOpenUrl('/pages/login/label?id=1', 99)
            } else {
                // 已注册  直接登录
                // store.commit(types.SET_PERMISSION, true)
                // window.location.href = store.state.beforeLoginRoute
				this.$handleOpenUrl('/pages/home/index', 0)
            }
        },        
    }
};
</script>

<style lang="scss" scoped>
#ccii_login_wx {
    height: 100%;
    background-color: #F7F9FE;
    .content {
        height:100%;
        margin: 0 20upx;
        background-color: #fff;
        padding: 20upx 40upx;
        border-radius: 16upx;
        // .back {
        //     display: flex;
        //     justify-content: center;
        //     align-items: center;
        //     width: 50upx;
        //     height: 50upx;
        //     background: rgba(0, 0, 0, .5);
        //     border-radius: 50%;
        //     .iconfont {
        //         font-size: 36upx;
        //         color: #fff;
        //     }
        //     .icon-zuojiantou {
        //         font-size: 44upx;
        //     }
        // }
        // p {
        //     margin: 35upx 0 0 30upx;
        // }
        .input_box {
            position: relative;
            height: 65upx;
            line-height: 65upx;
            border-bottom: 2upx solid #CCCCCC;
            display: flex;
            justify-content: center;
            margin: 60upx 0 0;
            input {
                height: 60upx;
                width: 100%;
            }
            .icon-guanbi1 {
                position: absolute;
                right: 200upx;
                color: #000;
                font-size: 34upx;
            }
            .code_btn {
               position: absolute;
               right: 0;
               height: 60upx;
			   line-height: 60upx;
			   font-size: 28upx;
			   z-index: 999999;
            }
            .c_blue {
                color: #00428E;
            }
        }
        .codes {
            position: relative;
			margin-top: 15upx;
            .hidden_input {
                position: absolute;
                bottom: 0;
                height: 60upx;
                width: 100%;
                z-index: 666;
                opacity: 0;
            }
			.input_code {
				.ul {
					display: flex;
					height: 60upx;
					width: 100%;
			
					.li {
						margin-right: 10upx;
						border-bottom: 2upx solid #999999;
						font-size: 32upx;
						display: flex;
						justify-content: center;
						align-items: center;
						box-pack: center;
						flex: 1;
					}
			
					.li:last-child {
						margin-right: 0upx;
					}
				}
			}
        }
        .btn {
            display: block;
            width: 520upx;
            height: 88upx;
            line-height: 88upx;
            background: linear-gradient(87deg, #035ABE,#218EED);
            border-radius: 44upx;
            color: #ffffff;
            text-align: center;
            font-size: 34upx;
            margin: 120upx auto 0;
        }
    }
}
</style>